import React, { useState, useEffect } from 'react';
import '../style/ARTAdd.css'
import { getTypeList, addArticle, updateArticle, getArticleDetail } from '../api/ARTAdd'
import { Row, Col, Input, Select, Button, message, Tag, Spin, Modal } from 'antd'
import { CheckCircleTwoTone } from '@ant-design/icons';
import Markdown from '../component/Markdown'
import MdToHtml from '../component/MdToHtml'
const { Option } = Select;
const { confirm } = Modal


function ARTAdd(props) {

  const [articleId, setArticleId] = useState(props.match.params.id || 0)   // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle, setArticleTitle] = useState('')   //文章标题

  const [articleContentMd, setArticleContentMd] = useState('')  // 文章内容
  const [introduceStr, setIntroduceStr] = useState('')  // 文章内容html

  const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
  const [selectedType, setSelectType] = useState(1) //选择的文章类别

  const [loading, setLoading] = useState(false)

  const size = ''

  useEffect(() => {
    typeList()
    if (!!articleId) getARTContent(articleId)
  }, [articleId])

  // 内容 md转html
  const changeContent = (text, html) => {
    setArticleContentMd(text)
    setIntroduceStr(html)
  }

  // 提取文章简介
  const htmlToIntroduce = (value) => {
    let hList = value.match(/(<h\d+[^>]*>(.*?)<\/h\d+>)/img) || []
    let introduce = ""
    hList.forEach(element => {
      introduce += element.match(/>(.*?)</)[1] + `  `;
    });
    if (!hList.length) {
      let pList = value.match(/[^><]+(?=<\/p>)/img) || []
      pList.forEach(element => {
        introduce += element + `  `;
      });
    }
    return introduce
  }

  // 获取类别列表
  const typeList = () => {
    getTypeList()
      .then(res => {
        console.log(res)
        setTypeInfo(res.list)
      })
      .catch(err => {
        console.log(err)
      })
  }

  // 获取要修改的文章
  const getARTContent = (id) => {
    setLoading(true)
    getArticleDetail(id)
      .then(res => {
        setLoading(false)
        let data = res.data
        setArticleTitle(data.title)
        setSelectType(data.typeId)
        setArticleContentMd(data.content)
        setIntroduceStr(MdToHtml(data.content))
      })
      .catch(err => {
        console.log(err)
        message.error('文章获取失败，请刷新后重试')
      })
  }

  // 验证信息的完整性
  const verifyIntegrity = () => {
    if (!articleContentMd) {
      message.warning('文章内容不能为空')
      return false
    } else if (!articleTitle) {
      message.warning('文章名称不能为空')
      return false
    }
    return true
  }

  // 重置内容
  const resetART = () => {
    setArticleId(0)
    setArticleTitle("")
    setIntroduceStr("")
    setArticleContentMd("")
  }

  // 保存文章
  const saveART = (status) => {
    if (!verifyIntegrity()) return false
    let data = {
      type_id: selectedType,
      title: articleTitle,
      introduce: htmlToIntroduce(introduceStr),
      content: articleContentMd,
      status: status
    }
    const txt = status ? "发布" : "保存"
    if (!articleId) {
      addArticle(data)
        .then(res => {
          // message.success('文章' + txt + '成功')
          setArticleId(res.insertId)
          submitOk(txt)
        })
        .catch(err => {
          message.error('文章' + txt + '失败')
        })
    } else {
      data.id = articleId
      updateArticle(data)
        .then(res => {
          // message.success('文章' + txt + '成功')
          submitOk(txt)
        })
        .catch(err => {
          message.error('文章' + txt + '失败')
        })
    }
  }

  // 发布成功的回调
  const submitOk = (value) => {
    confirm({
      title: value + '成功！',
      icon: <CheckCircleTwoTone twoToneColor="#52c41a" />,
      content: '您想继续发布“新的”文章还是继续“修改”此文章？',
      okText: '添加',
      cancelText: '修改',
      onOk() {
        resetART()
        props.history.push('/console/artAdd')
      },
      onCancel() { },
    });
  }

  return (
    <div>
      <Spin spinning={loading} delay={500}>
        <Row gutter={5}>
          <Col span={24}>
            <Row gutter={10} className="row-style">
              <Col span={14}>
                <Input
                  placeholder="博客标题"
                  size={size}
                  value={articleTitle}
                  onChange={(e) => { setArticleTitle(e.target.value) }} />
              </Col>
              <Col span={4} align="right">
                <Select
                  defaultValue={1}
                  value={selectedType}
                  onSelect={(value) => { setSelectType(value) }}
                  size={size}
                  style={{ width: '100%' }}>
                  {
                    typeInfo.map((item, index) => (<Option key={index} value={item.id}>{item.typeName}</Option>))
                  }>
              </Select>
              </Col>
              <Col span={6} align="right">
                <Tag color="green" size={size} style={{ display: !articleId ? '' : 'none' }}> 新文章 </Tag>
                <Tag color="red" size={size} style={{ display: !articleId ? 'none' : '' }}> 重新编辑 </Tag>
                <Button onClick={saveART.bind(this, 0)} danger size={size}>保存草稿</Button>
                <Button type="primary" onClick={saveART.bind(this, 1)} style={{ marginLeft: "10px" }} size={size}>发布文章</Button>
              </Col>
            </Row>
            <Row gutter={10} className="md-div">
              <Col span={24}>
                <Markdown
                  value={articleContentMd}
                  changeContent={changeContent}
                />
              </Col>
            </Row>
          </Col>
        </Row>
      </Spin>
    </div>
  )
}
export default ARTAdd